﻿function initRegisterDialog() {
	var tips = $("#validateTips");
	var name = $("#name"), email = $("#email"), password = $("#password"), repeat = $("#repassword"), allFields = $(
			[]).add(name).add(email).add(password).add(repeat);

	function updateTips(t) {
		tips.text(t).effect("highlight", {}, 3000);
	}

	function checkLength(o, n, min, max) {
		var len = o.val().replace(/[^\x00-\xff]/g, 'xx').length;
		if (len > max || len < min) {
			o.addClass('ui-state-error');
			updateTips(_('lenRegex', [ min, max ]));
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp(o, regexp, n) {
		if (!(regexp.test(o.val()))) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}
	}

	function checkEqual(repeat, pwd, n) {
		var ret = (repeat.val() == pwd.val());
		if (ret == false) {
			repeat.addClass('ui-state-error');
			updateTips(n);
		}
		return ret;
	}
   
   
  $('#registerDialogInfo').dialog({
  	  hide : '',
			autoOpen : false,
			resizable : false,
			width : 456,
			modal : true,
			title : _('createdUser'),
			overlay : {
				opacity : 0.5,
				background : "black"
			},
			buttons: {
				'确 定': function() {
					$(this).dialog('close');
				}
		 }

	});
	$('#registerDialog').dialog({
			hide : '',
			autoOpen : false,
			resizable : false,
			width : 690,
			modal : true,
			title : _('newUser'),
			overlay : {
				opacity : 0.5,
				background : "black"
			},
			buttons : {
				'提交' : function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');
					// From jquery.validate.js (by joern),
					// contributed by Scott Gonzalez:
					// http://projects.scottsplayground.com/email_address_validation/
				bValid = bValid && checkLength(name, "username", 4, 16);
				bValid = bValid && checkRegexp(name,/^[a-z\u4e00-\u9fa5]([0-9a-z_\u4e00-\u9fa5])+$/i,_('userNameRegex'));
				bValid = bValid && checkRegexp(email,/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,_('emailRegex'));
				bValid = bValid && checkLength(password, "password", 6, 16);
				bValid = bValid && checkRegexp(password, /^([0-9a-zA-Z_,!@#$&])+$/, _('passwordRegex'));
				bValid = bValid && checkEqual(repeat, password, _('repeatPwdRegex'));
				if (bValid) {
				    registerUser();
				}
			},
			'取消' : function() {
				$(this).dialog("close");
			},
			'重置' : function() {
				$(this).children('form')[0].reset();
				allFields.val('').removeClass('ui-state-error');
			}
			}
		// end of buttons
     });// end of dialog

	$('#registerForm').attr('action',FS.getRealPath('/createUser.do'));
	$('#registerDialog').dialog('open');
	$('#registerForm').resetForm();
}

function registerUser(){
	$('#registerForm').ajaxSubmit({  
        type:'POST',  
        dataType:'json', 
        beforeSubmit:  function(){
        	$('#registerMessage').html("正在提交注册信息，请稍候...");
        	$('#registerForm :input').attr('disabled', 'true');
        }, 
        resetForm:true,  
        success:function(response){ 
	        	var code=response.resultCode;
		 		switch(code){
		 		   case 0:   $('#registerDialog').dialog("close");
		 		             $('#registerDialogInfo').dialog('open');
		 		              _registerOK(response.data);
		 		            
		 		   					break;
		 		   case 1:  _warn('#resultMessage','服务器出错！');break;
		 		   case 2:	_warn('#resultMessage','用户注册失败！');break;
		 		}
		 		$('#registerMessage').html('');
		 		$('#registerForm :input').attr('disabled', '');
        }  
    });  
}


$('#userLogoutDialog').dialog({
	hide : '',
	autoOpen : false,
	resizable : false,
	width : 456,
	modal : true,
	title : _('createdUser'),
	overlay : {
		opacity : 0.5,
		background : "black"
	    },
	buttons: {
		'确 定': function() {
		   $(this).dialog('close');
		   performLogout();
	    },
	    '取消': function() {
	    	$(this).dialog('close');
	    }
    }

});

function _warn(id,msg){
	 $(id).html(msg).effect("highlight", {}, 2000).fadeOut(1000);
}

function _registerOK(user){
	   var t=5;
	    var timeout=t*1000;
	    $('#resultMessage').html("恭喜，注册成功！");
	    var timer=$('#resultMessage').everyTime(1000,function(i) {
				   $(this).html("恭喜，注册成功！本窗口将在"+(t--)+"秒钟后自动关闭...").effect("highlight", {}, 1000);
			});
		$('#uid').html(user.id);
	    $('#uname').html(user.name);
	    $('#uemail').html(user.email);
	    $('#uqq').html(user.qq);
	    $('#umobile').html(user.mobile);
	    $('#registerDialogInfo').oneTime(timeout, function() {
	    	$('#resultMessage').html("");
	    	timer.stopTime();
	        $(this).dialog('close');
	        _loginOK(user);
	   });
}

 
function _loginOK(user){
	 FS.setCurrentUser(user);
	 $('#loginForm').hide();
	 $('#userInfo_uname').html(user.name);
	 $('#userInfo_uemail').html(user.email);
	 $('#userInfo_unameLogout').val(user.name);
	 $('#userInfo').show();
}

function _logoutOK(){
	FS.setCurrentUser(null);
	$('#loginForm').show();
	$('#userInfo_uname').html('');
	$('#userInfo_uemail').html('');
	$('#userInfo').hide();
}

function performLogout(){
	 
	$('#userInfoForm').ajaxSubmit({  
        type:'POST',  
        dataType:'json', 
        beforeSubmit:  function(){
	 			$('#userInfoMsg').html("正在注销，请稍候...");
	 			$('#userInfoForm :input').attr('disabled', 'true');
	 	}, 
        resetForm:true,  
        success:function(response){
	 		var code=response.resultCode;
	 		if(code==0){
	 			_logoutOK();
	 		}else{
	 			$('#userInfoMsg').html("服务器错误！");
	 		}
	 		$('#userInfoForm :input').attr('disabled', '');
	 		$('#userInfoMsg').html('');
	 	}
  });
}

//*************** button actions *************************/

function performLogin(){
	
	 if($('#loginName').val()=='' || $('#loginPassword').val()==''){
		 _warn('#loginModuleMsg','用户名或密码不能为空！');
	 }else{
		 $('#registerForm').attr('action',FS.getRealPath('/loginUser.do'));
		 $('#loginForm').ajaxSubmit({  
		        type:'POST',  
		        dataType:'json', 
		        beforeSubmit:  function(){
			 			$('#loginModuleMsg').html("正在登录，请稍候...");
			 			$('#loginForm :input').attr('disabled', 'true');
			 	}, 
		        resetForm:true,  
		        success:function(response){ 
				 		var code=response.resultCode;
				 		switch(code){
				 		   case 0:  _loginOK(response.data);break;
				 		   case 1:  _warn('#loginModuleMsg','该用户尚未注册！');
				 		   			break;
				 		   case 2:	_warn('#loginModuleMsg','用户名或密码错误！'); 
				 		   			break;
				 		}
				 		$('#loginForm :input').attr('disabled', '');
				 		$('#loginModuleMsg').html('');
		     }
		 });
	 }
}

$('#login').click(function() {
	performLogin();
});
/*
 * perform register user
 */
$('#reg').click(function() {
	$.queueModule('registerModule','', initRegisterDialog);
});

$('#myMessage').click(function() {
	 alert("show my messages");
});
$('#allMessage').click(function() {
	alert("show all Message");
});

$('#update').click(function() {
	alert("update my info");
	$('#registerDialog').dialog('open');
	$('#registerForm').resetForm();
});
/*
 * perform logout user
 */
$('#logout').click(function() {
	 alert("注销！");
	 $('#userInfoForm').attr('action',FS.getRealPath('/logoutUser.do'));
	 performLogout();
	 //$('#userLogoutDialog').dialog('open');
});


$('#loginModule').keyup(function(event){
    if (event.keyCode == 13) {
    	
       performLogin();
    }
});

function initLogin(){
	if(FS.isUserValid){
		 var user=FS.getCurrentUser();
	     $('#loginForm').hide();
		 $('#userInfo_uname').html(user.name);
		 $('#userInfo_uemail').html(user.email);
		 $('#userInfo_unameLogout').val(user.name);
		 $('#userInfo').show();
	  }
}


initLogin();